from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from model import Student, CourseNew

# 1. 链接数据库等准备工作
engine = create_engine('mysql+pymysql://root:python@localhost:3306/19python')
DBSession = sessionmaker(bind=engine)
session = DBSession()

# 2. 插入数据
# 创建Student对象
stu01 = Student(name='zhangsan', age=17)
stu02 = Student(name='xiaoming', age=19)
stu03 = Student(name='xiaohong', age=18)
stu04 = Student(name='lilei', age=22)
stu05 = Student(name='hanmeimei', age=21)

# 创建Course对象
c1 = CourseNew(name='舞蹈')
c2 = CourseNew(name='礼仪')
c3 = CourseNew(name='演讲')
c4 = CourseNew(name='金融')

# 每个学生选课信息添加好
stu01.courses = [c1, c2]
stu02.courses = [c3]
stu03.courses = [c2, c3]
stu04.courses = [c1, c3, c4]
stu05.courses = [c2, c4]

# 如添加到数据库
session.add_all([stu01, stu02, stu03, stu04, stu05, c1, c2, c3, c4])

# 3. 提交（只要是增删改任意一种都意味着对数据进行了修改，都需要commit）
session.commit()

# 4. 关闭session
session.close()
